package com.kotiln.lgc.lib_network

import android.util.Log
import com.kotiln.lgc.lib_network.http.HttpKey
import com.kotiln.lgc.lib_network.http.HttpUrl
import com.kotiln.lgc.lib_network.http.ServiceCreator
import com.kotiln.lgc.lib_network.impl.HttpImplService
import com.kotiln.lgc.lib_network.interceptor.HttpInterceptor
import okhttp3.OkHttpClient
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.lang.RuntimeException
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

/**
 *@fileName HttpManager
 *@date2021/1/25  15:32
 *@author HttpManager$
 *@describe TODO
 *@desc 对外的网络管理类
 */
object HttpManager {

    //---------------------------------Jetpack 协程------------------------------------------------------
//    private val httpImplService:HttpImplService=ServiceCreator.create<HttpImplService>()
    //查询天气
//    suspend fun queryWeather(city:String)= httpImplService.getWeather(city,HttpKey.WEATHER_KEY).await()

    private suspend fun <T> Call<T>.await():T{
        return suspendCoroutine {
                continuation ->enqueue(object: Callback<T> {
            override fun onResponse(call: Call<T>, response: Response<T>) {
                val body=response.body()
                if(body!=null)continuation.resume(body)
                else continuation.resumeWithException(RuntimeException("response body is null"))
            }

            override fun onFailure(call: Call<T>, t: Throwable) {
                continuation.resumeWithException(t)
            }

        })
        }
    }


    //-----------------------------------普通Retrofit------------------------------------------------------------

    //创建客户端
    //private fun getClient():OkHttpClient{
        //return OkHttpClient.Builder().addInterceptor(HttpInterceptor()).build()
    //}

    //天气对象
    //private val retrofitWeather:Retrofit by lazy {
       // Retrofit.Builder().client(getClient()).baseUrl(HttpUrl.WEATHTER_BASE_URL)
           // .addConverterFactory(GsonConverterFactory.create()).build()
    //}

    //天气接口对象
    private val apiWeather:HttpImplService by lazy{
        //retrofitWeather.create(HttpImplService::class.java)
        ServiceCreator.create<HttpImplService>()
    }

    //查询天气
     fun queryWeather(city:String):Call<ResponseBody>{
         return apiWeather.getWeather(city,HttpKey.WEATHER_KEY)
//    return httpImplService.getWeather(city,HttpKey.WEATHER_KEY).await()
    }

}


